package com.jungle.mvvm.sample.ui.home;

import android.annotation.SuppressLint;
import android.app.Application;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableList;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;


import com.jungle.mvvm.base.BaseViewModel;
import com.jungle.mvvm.base.MultiItemViewModel;
import com.jungle.mvvm.binding.command.BindingCommand;
import com.jungle.mvvm.sample.BR;
import com.jungle.mvvm.sample.R;
import com.jungle.mvvm.sample.app.WanObserver;
import com.jungle.mvvm.sample.bean.ArticleBean;
import com.jungle.mvvm.sample.bean.BannerBean;
import com.jungle.mvvm.sample.bean.HomeBean;
import com.jungle.mvvm.sample.bean.ListBean;
import com.jungle.mvvm.sample.bean.SameBean;
import com.jungle.mvvm.sample.http.WanNetwork;
import com.jungle.mvvm.utils.KLog;
import com.jungle.mvvm.utils.ToastUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

/**
 * @ClassName HomeViewModel
 * @Description HomeViewModel
 * @Author Daniel
 * @Version V1.0.0
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class HomeViewModel extends BaseViewModel {
    private boolean mRefresh = true;
    private boolean mOver = false;
    private int mSize = 0;
    private static final String MultiRecycleType_Head = "head";
    private static final String MultiRecycleType_Item = "item";

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public HomeViewModel(@NonNull Application application) {
        super(application);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if (MultiRecycleType_Head.equals(itemType)) {
                //设置头布局
                itemBinding.set(BR.viewModel, R.layout.item_home_head);
            } else if (MultiRecycleType_Item.equals(itemType)) {
                //设置左布局
                itemBinding.set(BR.viewModel, R.layout.item_home);
            }
        }
    });

    public class UIChangeObservable {
        //下拉刷新完成
        public ObservableBoolean finishRefreshing = new ObservableBoolean(false);
        //上拉加载完成
        public ObservableBoolean finishLoadmore = new ObservableBoolean(false);
    }

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(() -> initData());

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(() -> {
        mRefresh = false;
        if (mOver) {
            ToastUtils.showShort("没有更多数据了！");
            changeState();
        } else {
            getData();
        }
    });

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initData() {
        this.mSize = 0;
        this.mRefresh = true;
        getBanner();
    }

    @SuppressLint("CheckResult")
    private void getData() {
        showDialog("数据加载中……");
        OtherModel.getHomeArticle(mSize)
                .compose(WanNetwork.applyService(getLifecycleProvider(), new WanObserver<ListBean<List<ArticleBean>>>() {
                    @Override
                    public void onWanSuccess(ListBean<List<ArticleBean>> listWanBean) {
                        changeState();
                        mOver = listWanBean.getData().getOver();
                        List<ArticleBean> list = listWanBean.getData().getDatas();
                        if (mRefresh) {
                            observableList.clear();
                        }
                        mSize = mSize + 1;
                        MultiItemViewModel itemViewModel;
                        for (ArticleBean articleBean : list) {
                            itemViewModel = new HomeItemViewModel(HomeViewModel.this, articleBean);
                            itemViewModel.multiItemType(MultiRecycleType_Item);
                            observableList.add(itemViewModel);
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onWanFailure(String e) {
                        changeState();
                        dismissDialog();
                        KLog.e(e);
                    }
                }));
    }

    @SuppressLint("CheckResult")
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void getBanner() {
        showDialog("数据加载中……");
        Observable<SameBean<List<BannerBean>>> bannerList = OtherModel.getBannerList().subscribeOn(Schedulers.io());
        Observable<ListBean<List<ArticleBean>>> homeArticle = OtherModel.getHomeArticle(mSize).subscribeOn(Schedulers.io());

        Observable.zip(bannerList, homeArticle, (listSameBean, listListBean) -> new HomeBean(listSameBean, listListBean)).observeOn(AndroidSchedulers.mainThread())
                .subscribe(homeBean -> {
                    dismissDialog();
                    changeState();
                    observableList.clear();
                    SameBean<List<BannerBean>> banners = homeBean.getBanners();
                    ListBean<List<ArticleBean>> articles = homeBean.getArticles();
                    MultiItemViewModel itemViewModel;
                    if (banners.getErrorCode() == 0) {
                        itemViewModel = new HomeHeadViewModel(HomeViewModel.this, banners.getData());
                        itemViewModel.multiItemType(MultiRecycleType_Head);
                        observableList.add(itemViewModel);
                    }
                    if (articles.getErrorCode() == 0) {
                        mOver = articles.getData().getOver();
                        List<ArticleBean> list = articles.getData().getDatas();
                        mSize = mSize + 1;
                        for (ArticleBean articleBean : list) {
                            itemViewModel = new HomeItemViewModel(HomeViewModel.this, articleBean);
                            itemViewModel.multiItemType(MultiRecycleType_Item);
                            observableList.add(itemViewModel);
                        }
                    }
                });
    }

    private void changeState() {
        if (mRefresh) {
            uc.finishRefreshing.set(!uc.finishRefreshing.get());
        } else {
            uc.finishLoadmore.set(!uc.finishLoadmore.get());
        }
    }
}

